<?php

namespace App\Http\Controllers\Balance;

use App\Http\Controllers\BaseController;
use App\Models\Balance\Balance as ModelsBalance;
use App\Models\Balance\BalanceLog as ModelsBalanceLog;
use App\Models\Custom\Custom;
use App\Models\Manger\Manger;
use App\Models\Settle\SettleCompany;
use App\Services\Balance\Balance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;


class BalanceController extends BaseController
{

    /**
     * 期初余额列表
     */
    public function getbalancelist(Request $request)
    {
        $category = $request->category ?? 1;
        if (!in_array($category, [1, 2])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $list = ModelsBalance::getList($request, $this->mangerinfo['cpid'], $category);

        //增加往来单位 业务员_往来单位名称_结算公司
        if($list['list']){
            foreach ($list['list'] as $k=>$v){
                //获取结算公司的 真实名称
                if($v['custom_info']){
                    if (is_numeric($v['custom_info']['settlement_company'])) {
                        $settlement_company = SettleCompany::where([['id', (int)$v['custom_info']['settlement_company']]])->first();
                        if ($settlement_company) {
                            $settlement_company = $settlement_company->toArray();
                            $list['list'][$k]['custom_info']['settlement_company'] = $settlement_company['settle_company_name'];
                        } else {
                            $list['list'][$k]['custom_info']['settlement_company'] = '';
                        }
                    } else {
                        $list['list'][$k]['custom_info']['settlement_company'] = $v['custom_info']['settlement_company'];
                    }

                    //获取 业务员名称
                    if (!empty($v['manger_id'])) {
                        $manger = Manger::where(['id' => $v['custom_info']['manger_id']])->first();
                        if ($manger) {
                            $manger = $manger->toArray();
                            $list['list'][$k]['custom_info']['manger_name_new'] = $manger['realname'];
                        } else {
                            $list['list'][$k]['custom_info']['manger_name_new'] = '';
                        }
                    } else {
                        $list['list'][$k]['custom_info']['manger_name_new'] = '';
                    }


                    $tplus_company_name = $list['list'][$k]['custom_info']['manger_name'].'-'.$list['list'][$k]['custom_info']['company_name'].'*'.$list['list'][$k]['custom_info']['settlement_company'];
                    $list['list'][$k]['custom_info']['tplus_company_name'] = $tplus_company_name;
                }
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 更改期初余额
     */
    public function resetbalance(Request $request)
    {
        $custom_id = intval($request->custom_id);
        $changeby_manger_id = $this->mangerinfo['id'];
        $balance = intval($request->balance);

        $cpid = $this->mangerinfo['cpid'];
        /***
         *  查询客户/供应商 是否审核通过，通过后才可以操作
         *
         */
        $customInfo = Custom::where('id',$custom_id)->first();
        if($customInfo['custom_status'] !='3' || $customInfo['invoice_status'] !='3'){
            return response()->json(['code' => '001', 'msg' => '客户/供应商审核通过后，方可设置期初余额']);
        }
        $info = ModelsBalance::where(['cpid' => $cpid, 'custom_id' => $custom_id])->first();

        if($info->balance_init_at>0){
            return response()->json(['code' => '001', 'msg' => '期初余额已设置，请勿重复设置']);
        }
        try {
            Balance::resetBalance($custom_id, $balance, $changeby_manger_id, $this->mangerinfo['cpid']);
        } catch (\Exception $e) {
            return response()->json(['code' => '001', 'msg' => $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 余额流水
     */
    public function getbalanceloglist(Request $request)
    {
        $category = $request->category ?? 1;
        if (!in_array($category, [1, 2])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $list = ModelsBalanceLog::getList($request, $category, $this->mangerinfo['cpid']);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 获取客户/供应商余额
     */
    public function getcustombalance(Request $request)
    {
        $custom_id = intval($request->custom_id);
        $cpid = $this->mangerinfo['cpid'];
        $info = ModelsBalance::where(['cpid' => $cpid, 'custom_id' => $custom_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $balance = ModelsBalance::where(['cpid' => $cpid, 'custom_id' => $custom_id])->value('balance');

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['balance' => $balance]]);
    }



    /**
     * 模板下载
     */
    public function dodownload(Request $request)
    {
        $category = $request->category;
        if ($category == 1) {
            $filenmame = '/template/销售客户期初余额导入模板.xlsx';
        } else {
            $filenmame = '/template/供应商期初余额导入模板.xlsx';
        }

        if (file_exists(storage_path() . $filenmame) && is_file(storage_path() . $filenmame)) {
            ob_clean();
            return response()->download(storage_path() . $filenmame);
        }
        return response()->json(['code' => '001', 'msg' => '文件不存在，下载失败'], 200);
    }

    /**
     * 上传导入，先调用uploadfile，返回地址调用该接口
     */
    public function doimport(Request $request)
    {
        $filepathname = $request->filepathname;
        $category = $request->category;    //1客户2供应商
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $custom_arr = Excel::toArray(null, $file)[0];
            if ((count($custom_arr) < 2)) {
                return response()->json(['code' => '001', 'msg' => '请填写客户信息'], 200);
            }

            $import = [];

            if(count($custom_arr[0])!=2){
                return response()->json(['code' => '001', 'msg' => '请上传正确模版'], 200);
            }

            unset($custom_arr[0]);

            foreach ($custom_arr as $custom) {
                $import[$custom[0]]['category'] = $category;
                $import[$custom[0]]['code'] = $custom[0];       //客户编码或者供应商编码
                $import[$custom[0]]['balance'] = $custom[1]*100;    //需要修改的期初余额
            }

            $mangerinfo = $this->mangerinfo;

            $cpid = $mangerinfo['cpid'] ?? 0;
            $manger_id = $mangerinfo['id'] ?? 0;
            $manger_name = $mangerinfo['realname'] ?? '';

            if($category == 1) {
                foreach ($import as $key => $item) {
                    if (empty($item['code'])) {
                        continue;
                    }
                    $customInfo = Custom::where(['code'=>$item['code'],'category'=>1])->first();
                    if($customInfo['custom_status'] !='3' || $customInfo['invoice_status'] !='3'){
                        return response()->json(['code' => '001', 'msg' => '客户编码:'.$item['code'].'审核通过后，方可设置期初余额']);
                    }
                    $custom_id = $customInfo['id'];
                    $info = ModelsBalance::where(['cpid' => $cpid, 'custom_id' => $custom_id])->first();

                    if($info->balance_init_at>0){
                        return response()->json(['code' => '001', 'msg' => '期初余额已设置，请勿重复设置']);
                    }
                    $import[$key]['custom_id'] = $custom_id;
                }

            }else{
                foreach ($import as $key => $item) {
                    if (empty($item['code'])) {
                        continue;
                    }
                    $customInfo = Custom::where(['company_code'=>$item['code'],'category'=>2])->first();
                    if($customInfo['custom_status'] !='3' || $customInfo['invoice_status'] !='3'){
                        return response()->json(['code' => '001', 'msg' => '供应商编码:'.$item['code'].'审核通过后，方可设置期初余额']);
                    }
                    $custom_id = $customInfo['id'];
                    $info = ModelsBalance::where(['cpid' => $cpid, 'custom_id' => $custom_id])->first();

                    if($info->balance_init_at>0){
                        return response()->json(['code' => '001', 'msg' => '期初余额已设置，请勿重复设置']);
                    }
                    $import[$key]['custom_id'] = $custom_id;
                }
            }

            DB::beginTransaction();
            try {
                foreach ($import as $item) {
                    if (empty($item['code'])) {
                        continue;
                    }
                    Balance::resetBalance($item['custom_id'], $item['balance'], $manger_id, $cpid);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '修改期初余额失败，' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '操作成功'], 200);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }
}
